package com.unknowpupil.sell.config.swagger;


import com.unknowpupil.sell.common.Common;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.List;

import static com.google.common.collect.Lists.newArrayList;

/**
 * @Classname: Swagger2Config
 * @Author: <a> w10g </a>
 * @CreateDate: Create in 2019/12/19 11:49
 * @Description:  .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)) 扫描通过ApiOperation注解的
 * @Version: 1.0
 */
@EnableSwagger2
@Configuration
public class Swagger2Config {
    @Value(value = "${swagger2.enabled}")
    Boolean Enabled;
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2).
                apiInfo(apiInfo())
                .useDefaultResponseMessages(Enabled)
                .groupName("Api_Sell")
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.unknowpupil.sell.controller"))
                .paths(PathSelectors.regex("^(?!api).*$"))
                .build().pathMapping("/")
                .securitySchemes(securitySchemes())
                .securityContexts(securityContexts())
                ;
    }
    private List<ApiKey> securitySchemes() {
        return newArrayList(
                new ApiKey(Common.ADMIN_ACCESS_TOKEN, Common.ADMIN_ACCESS_TOKEN, "header"));
    }
    private List<SecurityContext> securityContexts() {
        return newArrayList(
                SecurityContext.builder()
                        .securityReferences(defaultAuth())
                        .forPaths(PathSelectors.regex("^(?!api).*$"))
                        .build()
        );
    }
    List<SecurityReference> defaultAuth() {
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        return newArrayList(
                new SecurityReference(Common.ADMIN_ACCESS_TOKEN, authorizationScopes));
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("API")
                .description("©2019 Copyright. Powered By w10g.")
                .contact(new Contact("unknowpupil", "http://unknowpupil.cn", "unknowpupil@163.com"))
                .version("1.0")
                .build();
    }
}
